package stock.controller;

import cloudentity.model.Stock;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import stock.bean.TestObject;
import stock.mapper.UserMapper;
import stock.model.User;
import stock.service.StockService;
import stock.service.impl.UserServiceImpl;
import stock.utils.JedisUtil;
import stock.utils.RedisUtil;
import stock.utils.Result;

import java.util.*;

@RestController
@RequestMapping("stock")
@Slf4j
public class StockController {
    @Autowired
    Gson gson;

    //======================Mysql相关======================
    @Autowired
    private StockService stockService;
    @GetMapping("/findById{id}")
    public  Object findById(@PathVariable("id") Integer id){
        Stock stock = this.stockService.deduct(id);
        return stock;
    }

    @Autowired
    private UserServiceImpl userService;

    @GetMapping("find/one{id}")
    public Object findOne(@PathVariable("id") Integer id){
        System.out.println("======"+id);
//        List<User> user = userService.list();
        User user = userService.getById(id);
        return Result.success(user);
    }

    @GetMapping("find/list")
    public Object findList(){
        List<User> list = userService.list();
        Iterator it = list.iterator();
        if(it.hasNext()){
            System.out.println(it.next());
        }
        return Result.success(list);
    }

    @Autowired
    UserMapper userMapper;
    @RequestMapping("find/by/page")
    public Object findByPage(@RequestParam(value="page",defaultValue = "1") Integer p,
                             @RequestParam(value="limit",defaultValue = "10") Integer size
    ){
        System.out.println("===="+p+"----"+size);//+"==="+pa+"----"+li
        Page<User> userPage = new Page<>(p,size,true);
        Page<User> page = userService.page(userPage);
//        userMapper.selectPage(page,status);
        return Result.success(page);
    }

    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/jdbc/template")
    public Result jdbcTemplate(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from for_stock order by id desc;");
        for(int i = 0; i < list.size(); i++){
            System.out.println(list.get(i));
        }
        return Result.success(list);
    }

    //======================Redis相关======================
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    JedisUtil jedisUtil;

    @Autowired
    RedisUtil redisUtil;
    /**
     * redis测试 包含JSON转换
     * @return
     */
    @GetMapping("/test/redis")
    public Object testRedis(){
        Logger logger = LoggerFactory.getLogger(getClass());
        logger.info(String.valueOf(redisConnectionFactory.getClass()));
        List l = new ArrayList();
        l.add(Math.random()*3);
        l.add(Math.random()*100);

        Map map = new HashMap<String,Object>();
        map.put("a","1");
        map.put("b","牛逼啊");

        //=============JedisUtil 操作==========
        Jedis jedis = jedisUtil.getInstance(1);
        jedis.set("JedisUtil","成功");
        logger.info("JedisUtil测试:"+jedisUtil.get("JedisUtil"));

        logger.error(String.valueOf(redisTemplate.getClass()));

        jedis.hmset("map2",map);

        jedisUtil.close();
        //=============stringRedisTemplate 操作==========
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        operations.set("stringRedisTemplate1", String.valueOf(Math.random()));

        stringRedisTemplate.opsForValue().set("abc","哈哈哈");//stringRedisTemplate直接设置没有被编码

        //=============redisUtil 操作==========
        logger.info("stringRedisTemplateList测试:"+redisUtil.get("redisTemplateList"));

        redisUtil.expire("stringRedisTemplate1",3600);

        redisUtil.set("map",map);
        logger.info("Gson转换:"+gson.toJson(map));

        //=============redisTemplate 操作==========
        redisTemplate.opsForValue().set("redisTemplateList",l);//redisTemplate key value 会被转码

        redisTemplate.opsForHash().put("map1","a","1");
        redisTemplate.opsForHash().put("map1","b","2");

        redisTemplate.opsForValue().set("redisTemplateMap",gson.toJson(map));//对象转换为字符串存储

        logger.info("redisTemplateMap:"+redisUtil.get("redisTemplateMap"));

        Object o = redisTemplate.opsForValue().get("redisTemplateMap");

        logger.info("stringRedisTemplateMap测试:"+o);


        String json = (String) redisTemplate.opsForValue().get("redisTemplateMap");

        //将JSON字符串解析为对象
        Map<String,String> jsonObject = gson.fromJson(json, new TypeToken<Map<String,String>>(){}.getType());

        System.out.println(jsonObject.get("a"));

        return Result.success(jsonObject);
    }

    @GetMapping("/test/json")
    public Object testJson(@RequestBody String string){
        Map<String,String>  map= gson.fromJson(string,new TypeToken<Map<String,String>>(){}.getType());
        if(map.get("a")=="true"){
            log.info("a有值："+map.get("a"));
        }else if(map.get("a")=="false"){
            log.info("a有值："+map.get("a"));
        }
        log.info(String.valueOf(map.get("c") == "10"));
        log.info(String.valueOf(map.get("c").equals("10")));
        if(map.get("c").equals("10")){
            log.info("c为10");
        }else{
            log.info("c无值："+map.get("c"));
        }
//        Map map = new HashMap<String,Object>();
//        map.put("a",string);
//        map.put("b",b);

        return Result.success(map);
    }

    @Autowired
    TestObject testObject;


    /**
     * 请求参数处理
     * @param object
     * @return
     */
    @PostMapping("/test/data")
    public Object testData(@RequestBody TestObject object){
        /*
            {
              "a": true,
              "b": "world",
              "c": 1000,
              "d": [
                {
                  "f": 1
                },
                {
                  "g": 2
                },
                {
                  "h": 3
                }
              ],
              "e": {"m": 1,"n": 2}
            }
         */
        if(object.getA()==true){
            object.setA(false);
        }else{
            object.setA(true);
        }
        if(object.getC()==10){
            object.setC(object.getC()*100);
        }
        if(object.getB().equals("hello")){
            object.setB("world");
        }
        Map d = (Map) object.getD().get(1);
        log.info("获取数组对象里面的某个键值："+d.get("g"));
        Integer m = (Integer) object.getE().get("m");
        if(m==1){
            log.info("获取到对象里的m:"+m);
        }
        return Result.success(object);
    }
}
